﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Cerulean;
using System.Diagnostics;
using System.Threading;

namespace TestCerulean
{
  public partial class MainPage : PhoneApplicationPage
  {
    // Constructor
    public MainPage()
    {
      InitializeComponent();
      System.EventHandler d1 = null;
      string filepath = "/Cerulean/testfolder/test.txt";
      d1 = (s1, e1) =>
      {
        //unhook the handler so it only fires once (SaveString updates the filesystem model)
        SkyDrive.Instance.FileSystemChanged -= d1;
        //create a file with some recognisable content
        SkyDrive.Instance.SaveString(filepath, "This is a test of folder and file creation.", true);
        //read the file from SkyDrive and emit the content to the output pane for inspection
        Debug.WriteLine("FileSystemChanged: {0}", SkyDrive.Instance.LoadString(filepath));
        //delete the file but not the path on SkyDrive
        SkyDrive.Instance.Delete(filepath);
      };
      SkyDrive.Instance.FileSystemChanged += d1;
      App.Current.UnhandledException += new EventHandler<ApplicationUnhandledExceptionEventArgs>(Current_UnhandledException);
      SkyDrive.Instance.Authenticate("username@live.com", "password");
      //The FileSystemChanged event won't fire unless authentication succeeds and the filesystem is read.
      //Authenticate throws UnauthorizedAccessException when it fails. This is asynchronous so handle it
      //at the application level and marshall onto the UI thread.
    }

    void Current_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
    {
      Dispatcher.BeginInvoke(() => { MessageBox.Show(e.ExceptionObject.Message); });      
    }
  }
}